<template>
  <div class="product-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>商品管理</h1>
          <el-button type="primary" @click="goToAdd"> 新增商品 </el-button>
        </div>

        <el-card>
          <div class="toolbar">
            <el-button :disabled="!selected.length" @click="batchEnable">批量启用</el-button>
            <el-button :disabled="!selected.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table :data="products" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" prop="shoeId" width="90" />
            <el-table-column label="名称" prop="name" />
            <el-table-column label="货号" prop="serialNumber" width="140" />
            <el-table-column label="价格" width="120">
              <template #default="{ row }">¥{{ row.discountPrice ?? row.price }}</template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-switch
                  :model-value="row.status === '1'"
                  :active-value="true"
                  :inactive-value="false"
                  @change="(val) => toggleStatus(row, !!val)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280">
              <template #default="{ row }">
                <el-button size="small" @click="goToEdit(row)">编辑</el-button>
                <el-button size="small" @click="openImages(row)">图片</el-button>
                <el-button size="small" type="danger" @click="deleteProduct(row.shoeId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 商品新增/编辑改为路由跳转 ProductEdit 全屏页 -->

    <ImageManagerDialog
      :visible="imageDialogVisible"
      :shoe-id="currentShoeId"
      title="商品图片管理"
      @close="imageDialogVisible = false"
      @uploaded="handleUploaded"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 提示：富文本已迁移到专用编辑页，此处不引用编辑器以避免未装依赖的类型报错
import { productService } from '@/api'
import type { Shoes } from '@/types'
import ImageManagerDialog from '@/components/ImageManagerDialog.vue'

const loading = ref(false)
const products = ref<Shoes[]>([])
const imageDialogVisible = ref(false)
const currentShoeId = ref<number>(0)
const selected = ref<Shoes[]>([])
// 分页相关状态
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
// 已迁移到 ProductEdit 页面
// const editing = ref(false)
// const editingId = ref<number | null>(null)
// 编辑字段已迁移到 ProductEdit 页面
// 废弃字段（保留类型兼容，当前未使用）
// 兼容类型（当前页面不再内联编辑）
// const statusSwitch = computed({ get: () => form.value.status === '1', set: (v: boolean) => { form.value.status = v ? '1' : '0' } })

const loadProducts = async () => {
  loading.value = true
  try {
    const res = await productService.getShoesListPage(page.value, pageSize.value)
    // 兼容 PageResult 或 map 结构
    const payload = res.data as unknown as { data?: unknown }
    const d = payload?.data as unknown
    let list: Shoes[] = []
    if (d && typeof d === 'object') {
      const maybeList = (d as { list?: unknown }).list
      if (Array.isArray(maybeList)) {
        list = maybeList as Shoes[]
      } else {
        const maybeInner = (d as { data?: unknown }).data
        if (maybeInner && typeof maybeInner === 'object') {
          const innerList = (maybeInner as { list?: unknown }).list
          if (Array.isArray(innerList)) {
            list = innerList as Shoes[]
          }
        }
      }
    }
    products.value = list
    
    // 获取总数
    if (d && typeof d === 'object') {
      const maybeTotal = (d as { total?: unknown }).total
      if (typeof maybeTotal === 'number') {
        total.value = maybeTotal
      } else {
        const maybeInner = (d as { data?: unknown }).data
        if (maybeInner && typeof maybeInner === 'object') {
          const innerTotal = (maybeInner as { total?: unknown }).total
          if (typeof innerTotal === 'number') {
            total.value = innerTotal
          }
        }
      }
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

const router = useRouter()

const goToAdd = () => router.push('/admin/products/add')
const goToEdit = (product: Shoes) => router.push(`/admin/products/${product.shoeId}/edit`)

// 废弃：改为路由跳转到全屏编辑页

const openImages = (product: Shoes) => {
  currentShoeId.value = product.shoeId
  imageDialogVisible.value = true
}

const deleteProduct = async (id: number) => {
  try {
    await productService.deleteShoes(id)
    await loadProducts()
  } catch (e) {
    console.error('删除商品失败', e)
  }
}

const toggleStatus = async (row: Shoes, val: boolean) => {
  try {
    await productService.updateShoesStatus(row.shoeId, val ? '1' : '0')
    await loadProducts()
  } catch (e) {
    console.error('修改状态失败', e)
  }
}

const handleSelectionChange = (rows: Shoes[]) => {
  selected.value = rows
}

const batchEnable = async () => {
  if (!selected.value.length) return
  await Promise.all(
    selected.value.map((item) => productService.updateShoesStatus(item.shoeId, '1')),
  )
  selected.value = []
  await loadProducts()
}

const batchDisable = async () => {
  if (!selected.value.length) return
  await Promise.all(
    selected.value.map((item) => productService.updateShoesStatus(item.shoeId, '0')),
  )
  selected.value = []
  await loadProducts()
}

const batchDelete = async () => {
  if (!selected.value.length) return
  await Promise.all(selected.value.map((item) => productService.deleteShoes(item.shoeId)))
  selected.value = []
  await loadProducts()
}

// 已改为跳转编辑页

const handleUploaded = () => {
  // 图片上传后可选择刷新列表或图片区域（此处刷新列表）
  loadProducts()
}

// 分页处理函数
const handlePageChange = (p: number) => {
  page.value = p
  loadProducts()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1 // 切换每页数量时重置到第一页
  loadProducts()
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.product-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
}

.toolbar {
  margin-bottom: 12px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
